#ifndef F_CPU
#define		F_CPU			16000000UL
#endif
#include <util/delay.h>
#include <avr/io.h>
#include "FreeRTOS_physical.h"
#include "eeprom.h"

#include "FreeRTOS_adc.h"
//unsigned char V_black[8] = {80,80,80,80,80,80,80,80};
//unsigned char V_white[8] = {120,120,120,120,120,120,120,120};
//unsigned char V_compare[8] = {100,100,100,100,100,100,100,100};

void init_ADC(void)
{
   // ADC initialization
    // ADC Clock frequency: 1000.000 kHz
    // ADC Voltage Reference: AVCC pin
    // Only the 8 most significant bits of
    // the AD conversion result are used
    ADMUX=ADC_VREF_TYPE & 0xff;
    ADCSRA=0x84;
}
// Read the 8 most significant bits
// of the AD conversion result
static unsigned char read_adc(unsigned char adc_input)
{
	ADMUX = adc_input | (ADC_VREF_TYPE & 0xff);
    // Delay needed for the stabilization of the ADC input voltage
    _delay_us(10);
    // Start the AD conversion
    ADCSRA|=0x40;
    // Wait for the AD conversion to complete
    while ((ADCSRA & 0x10)==0);
    ADCSRA|=0x10;
    return ADCH;
}
//Chua chong rung
void read_sensor(unsigned char *sensor_bits,unsigned char *_V_compare){ 
    unsigned char temp = 0,sensor_value =0;
	unsigned char i = 0;

	sensor_value = read_adc(0);
	
    for (i = 0; i < 8; i++){
       temp = temp << 1;
	   sensor_value = read_adc(i);
	   
       if (sensor_value > _V_compare[i]) 
			temp |= 0x01;
       else 
			temp &= 0xFE;
	}
	*sensor_bits = temp;
	
}

void save_sensor(unsigned char color, unsigned char *_V_compare)
{    
	unsigned char i = 0;   
    if(color == WHITE){
        for(i = 0; i < 8; i++){
            _V_compare[i]= read_adc(i) - 10;
        }
    } else {
        for(i = 0; i < 8;i++){
			_V_compare[i]= read_adc(i) + 10;
        }
    }
	write_Vcompare(_V_compare); 
}
/*
void Update_Vcompare(void){
    unsigned char i; 
    for(i = 0; i < 8 ; i++){ 
        V_compare[i] = V_black[i] + 10;
    }
	write_Vcompare(); 
}
*/
void read_Vcompare(unsigned char *_V_compare){
	eeprom_readstr(V_COMPARE_POS,_V_compare, 8);

}

void write_Vcompare(unsigned char *_V_compare){
	eeprom_writestr(V_COMPARE_POS, _V_compare, 8);
}

